package com.stox.ui.javafx.list.widget.menu.item;

import java.util.List;
import java.util.Locale;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.WatchList;
import com.stox.ui.javafx.list.client.WatchListClient;
import com.stox.ui.javafx.list.widget.menu.WatchListContextMenu;
import com.stox.ui.javafx.list.widget.menu.WatchListMenu;

@Component
public class DeleteWatchListOrEntryMenuItem extends MenuItem implements EventHandler<ActionEvent>, InitializingBean{

	@Autowired
	private WatchListClient watchListClient;
	
	@Autowired
	private ApplicationContext applicationContext;
	
	public DeleteWatchListOrEntryMenuItem() {
		setOnAction(this);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		setText(applicationContext.getMessage("Delete", null, Locale.getDefault()));
	}
	
	@Override
	public void handle(ActionEvent event) {
		WatchListContextMenu watchListContextMenu = (WatchListContextMenu)getParentPopup();
		TreeView<AbstractModel> treeView = watchListContextMenu.getTreeView();
		List<TreeItem<AbstractModel>> treeItems = treeView.getSelectionModel().getSelectedItems();
		for(TreeItem<AbstractModel> treeItem : treeItems){
			if(null != treeItem && null != treeItem.getValue() && !treeItem.equals(treeView.getRoot())){
				if(treeItem.getValue() instanceof WatchList){
					watchListClient.deleteWatchList(treeItem.getValue().getId());
					treeItem.getParent().getChildren().remove(treeItem);
					
					WatchListMenu removableMenu = null;
					for(WatchListMenu watchListMenu : WatchListMenu.getWatchListMenus()){
						if(treeItem.getValue().getId().equals(watchListMenu.getWatchList().getId())){
							removableMenu = watchListMenu;
						}
					}
					if(null != removableMenu){
						WatchListMenu.getWatchListMenus().remove(removableMenu);
						removableMenu.getParentMenu().getItems().remove(removableMenu);
					}
					
				}else{
					watchListClient.deleteWatchListEntry(treeItem.getValue().getId(), treeItem.getParent().getValue().getId());
					treeItem.getParent().getChildren().remove(treeItem);
				}
			}
		}
	}
	
}
